package com.fengr.org.controller;

import com.fengr.basic.AjaxResult;
import com.fengr.org.domain.Department;
import com.fengr.org.query.QueryDept;
import com.fengr.org.service.IDepartmentService;
import com.fengr.basic.util.PageList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping("/{id}")
    @ApiOperation(value = "查询一组数据",notes ="需要传入参数id" )
    public Department findOne(@PathVariable("id") Long id) {
        return departmentService.findOne(id);
    }

    @GetMapping
    @ApiOperation(value = "查询全部数据",notes = "不需要参数")
    public List<Department> findAll() {
        return departmentService.loadAll();
    }

    @PutMapping()
    @ApiOperation(value = "修改和添加",notes = "需要传一个对象参数，如果有id则是修改否则是添加")
    public AjaxResult addAndUpdata(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                departmentService.insert(department);
            } else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().getMessage("系统异常");
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除",notes = "需要传入参数id")
    public AjaxResult delete(@PathVariable Long id) {
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().getMessage("系统异常");
        }
    }

    @PostMapping()
    @ApiOperation(value = "分页查询",notes = "需要localpage和pagesize两个参数")
    public PageList<Department> list(@RequestBody QueryDept query) {
        try {
            return departmentService.pageList(query);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageList<>();
        }
    }
    @PatchMapping
    @ApiOperation(value = "批量删除",notes = "需要参数")
    public AjaxResult patchDelete(@RequestBody List<Long> ids) {
        try {
            departmentService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().getMessage("系统异常");
        }
    }
    @GetMapping("/tree")
    @ApiOperation(value = "获取部门树",notes = "不需要参数")
    public List<Department> getDeptTree(){
        return departmentService.getDeptTree();
    }
}